package com.atguigu.classroom.vod.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.classroom.vod.service.FileService;
import com.atguigu.classroom.vod.utils.ConstantPropertiesUtil;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Override
    public String uploadFile(MultipartFile file) {
        Auth auth=Auth.create(ConstantPropertiesUtil.ACCESSKEY,ConstantPropertiesUtil.SECRETKEY);
        String upToken = auth.uploadToken(ConstantPropertiesUtil.BUCKET);//上传凭证
        Configuration cfg=new Configuration(Region.region1());
        UploadManager uploadManager = new UploadManager(cfg);
        String key = ConstantPropertiesUtil.AVATAR+ UUID.randomUUID().toString().replace("-","");
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String res=null;
        try {
            Response response = uploadManager.put(file.getInputStream(), key, upToken,null,null);
            res=ConstantPropertiesUtil.URL+ JSONObject.parseObject(response.bodyString()).get("key");
        } catch (Exception exception) {
            exception.printStackTrace();
        }finally {
            return res;
        }
    }
}
